/**
 * Extension Error Handler
 * Handles errors related to VS Code extensions in the GitSummary app
 */

// Error types that we want to specifically handle
const EXTENSION_ERROR_TYPES = {
  FILESYSTEM_PROVIDER: 'FILESYSTEM_PROVIDER',
  LANGUAGE_STATUS: 'LANGUAGE_STATUS',
  EXTENSION_HOST: 'EXTENSION_HOST',
  UNKNOWN: 'UNKNOWN'
};

// Parses error messages to determine the type of extension error
function parseExtensionError(errorMessage) {
  if (errorMessage.includes('FAILED to register filesystem provider')) {
    return EXTENSION_ERROR_TYPES.FILESYSTEM_PROVIDER;
  } else if (errorMessage.includes('LanguageStatusItem')) {
    return EXTENSION_ERROR_TYPES.LANGUAGE_STATUS;
  } else if (errorMessage.includes('extensionHostProcess')) {
    return EXTENSION_ERROR_TYPES.EXTENSION_HOST;
  }
  return EXTENSION_ERROR_TYPES.UNKNOWN;
}

// Handles extension errors based on their type
function handleExtensionError(error) {
  const errorType = parseExtensionError(error.message || error.toString());
  
  // Log the error with context
  console.error(`Extension Error [${errorType}]:`, error);
  
  // Return user-friendly error info
  return {
    type: errorType,
    message: getUserFriendlyMessage(errorType, error),
    recoverable: isRecoverableError(errorType),
    extension: extractExtensionName(error.message || error.toString())
  };
}

// Provides user-friendly error messages
function getUserFriendlyMessage(errorType, error) {
  switch (errorType) {
    case EXTENSION_ERROR_TYPES.FILESYSTEM_PROVIDER:
      return `An extension failed to register its filesystem provider. This might affect file browsing functionality.`;
    case EXTENSION_ERROR_TYPES.LANGUAGE_STATUS:
      return `A language status component has been disposed. This might affect code assistance features.`;
    case EXTENSION_ERROR_TYPES.EXTENSION_HOST:
      return `The extension host process encountered an error. Some extensions might not work properly.`;
    default:
      return `An unknown extension error occurred. Some features might be unavailable.`;
  }
}

// Determines if an error is recoverable
function isRecoverableError(errorType) {
  return errorType !== EXTENSION_ERROR_TYPES.EXTENSION_HOST;
}

// Extracts extension name from error message
function extractExtensionName(errorMessage) {
  // Try to find extension ID in the format publisher.name
  const extensionMatch = errorMessage.match(/([a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+)-extension/);
  if (extensionMatch && extensionMatch[1]) {
    return extensionMatch[1];
  }
  
  // Try alternate format for language status items
  const statusMatch = errorMessage.match(/LanguageStatusItem.*from\s+([a-zA-Z0-9_.-]+)/);
  if (statusMatch && statusMatch[1]) {
    return statusMatch[1];
  }
  
  return 'Unknown Extension';
}

export { 
  handleExtensionError, 
  EXTENSION_ERROR_TYPES,
  parseExtensionError
};
